<template>
    <!-- 登录弹窗 -->
	<div class="relative z-50">
		<!-- 遮罩 -->
		<transition
			enter-active-class="transition-opacity duration-300 ease-out"
			leave-active-class="transition-opacity duration-300 ease-in"
			enter-from-class="opacity-0"
			leave-to-class="opacity-0"
		>
			<div v-if="visible" class="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs" @click="handleClose"></div>
		</transition>
		
		<!-- 抽屉 -->
		<transition
			enter-active-class="transition-all duration-300 ease-out"
			leave-active-class="transition-all duration-200 ease-in"
			enter-from-class="opacity-0 -translate-y-full"
			leave-to-class="opacity-0 -translate-y-full"
			appear
		>
			<div
				v-show="visible"
				class="fixed z-[51] top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[460px] bg-white shadow-2xl flex flex-col transform rounded-3xl"
			>
				<!-- 关闭按钮 -->
				<button
					class="absolute -top-6 -right-6 z-52 w-12 h-12 rounded-full !bg-white shadow-lg !cursor-pointer font-bold flex items-center justify-center text-3xl transition hover:!bg-neutral-200 hover:shadow-xl"
					@click="handleClose"
					aria-label="Close"
				>
					<icon-park-close theme="outline" size="18" fill="#000" />
				</button>
				<!-- 内容区 -->
				<div class="flex-1 min-h-0 overflow-y-auto relative">
					<!-- 表单容器 -->
					<div class="flex-1 bg-white rounded-3xl overflow-y-auto form-container overflow-x-hidden px-8 py-8" style="max-height: calc(90vh - 48px);">
						<template v-if="!isLoginForm">
							<h2 class="text-3xl font-medium font-playball mb-2 text-black">Create Account</h2>
							<p class="text-black/50 text-sm mb-4 font-poppins">Join our community of creators</p>
							
							<a-form 
								ref="signupFormRef"
								:model="signupFormData"
								:rules="signupFormRules"
								@submit="handleSignupSubmit"
								@submit-success="handleSignupSuccess"
								@submit-failed="handleSignupFailed"
								class="x-form"
							>
								<!-- Email -->
								<a-form-item
									field="email"
									class="!mb-6"
									hide-asterisk
								>
									<div class="flex flex-col relative justify-center border border-neutral-200 rounded-lg w-full px-3 py-2">
										<div class="text-black font-poppins font-medium text-sm mb-1">Email</div>
										<a-input
											v-model="signupFormData.email"
											placeholder="Enter your email"
											class="!bg-transparent !border-0 !rounded-lg !h-[36px]"
											allow-clear
										/>
									</div>
								</a-form-item>

								<!-- Verification Code -->
								<a-form-item
									field="code"
									class="!mb-6"
									hide-asterisk
								>
									<div class="flex flex-col relative justify-center border border-neutral-200 rounded-lg w-full px-3 py-2">
										<div class="text-black font-poppins font-medium text-sm mb-1">Verification Code</div>
										<div class="flex gap-3">
											<a-input
												v-model="signupFormData.code"
												placeholder="Enter verification code"
												class="flex-1 !bg-transparent !border-0 !rounded-lg !h-[36px]"
												allow-clear
											/>
											<a-button 
												type="outline" 
												:disabled="cooldown > 0"
												@click="sendcode"
												class="!h-[36px] !border-0 !text-black/80 !min-w-[100px] !rounded-lg hover:!border-rose-600"
											>
												<span v-if="cooldown > 0" class="text-black/50 font-poppins text-sm">
													Retry in {{ cooldown }}s
												</span>
												<span v-else class="text-black/60 font-poppins text-sm">
													Send Code
												</span>
											</a-button>
										</div>
									</div>
								</a-form-item>

								<!-- Password -->
								<a-form-item
									field="password"
									class="!mb-6"
									hide-asterisk
								>
									<div class="flex flex-col relative justify-center border border-neutral-200 rounded-lg w-full px-3 py-2">
										<div class="text-black font-poppins font-medium text-sm mb-1">Password</div>
										<a-input-password
											v-model="signupFormData.password"
											placeholder="Create a password"
											class="!bg-transparent !border-0 !rounded-lg !h-[36px]"
											allow-clear
										/>
									</div>
								</a-form-item>

								<!-- Register Button -->
								<a-button
									html-type="submit"
									type="primary"
									class="w-full font-poppins !h-[44px] !bg-rose-500 !border-none !text-white !text-[15px] !rounded-full !font-medium hover:!bg-rose-600 transition-colors"
									:loading="loading"
								>
									Create Account
								</a-button>

								<!-- Divider -->
								<div class="relative flex items-center justify-center my-4">
									<div class="flex-grow border-t border-neutral-200"></div>
									<span class="flex-shrink mx-4 text-neutral-400 font-poppins text-sm">Or continue with</span>
									<div class="flex-grow border-t border-neutral-200"></div>
								</div>

								<!-- Social Login -->
								<div class="flex items-center justify-center gap-4">
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-google theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-facebook theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-twitter theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-tiktok theme="filled" size="20" />
									</button>
								</div>

								<!-- Login Link -->
								<div class="text-center mt-4">
									<span class="text-neutral-500 font-poppins text-sm">Already have an account?</span>
									<a href="javascript:void(0)" class="text-rose-500 hover:text-rose-600 ml-1" @click="isLoginForm = true">Sign in</a>
								</div>
							</a-form>
						</template>
						<template v-else>
							<h2 class="text-3xl font-medium font-playball mb-2 text-black">Welcome Back</h2>
							<p class="text-black/50 text-sm mb-4 font-poppins">Sign in to your account</p>
							
							<a-form 
								ref="signinFormRef"
								:model="signinFormData"
								:rules="signinFormRules"
								@submit="handleSigninSubmit"
								@submit-success="handleSigninSuccess"
								@submit-failed="handleSigninFailed"
								class="x-form"
							>
								<!-- Email -->
								<a-form-item
									field="email"
									class="!mb-6"
									hide-asterisk
								>
								<div class="flex flex-col relative justify-center border border-neutral-200 rounded-lg w-full px-3 py-2">
									<div class="text-black font-poppins font-medium text-sm mb-1">Email</div>
										<a-input
											v-model="signinFormData.email"
											placeholder="Enter your email"
											class="!bg-transparent !border-0 !rounded-lg !h-[36px]"
											allow-clear
										/>
									</div>
								</a-form-item>

								<!-- Password -->
								<a-form-item
									field="password"
									class="!mb-6"
									hide-asterisk
								>
									<div class="flex flex-col relative justify-center border border-neutral-200 rounded-lg w-full px-3 py-2">
										<div class="text-black font-poppins font-medium text-sm mb-1">Password</div>
										<a-input-password
											v-model="signinFormData.password"
											placeholder="Enter your password"
											class="!bg-transparent !border-0 !rounded-lg !h-[36px]"
											allow-clear
										/>
									</div>
								</a-form-item>

								<!-- Login Button -->
								<a-button
									html-type="submit"
									type="primary"
									class="w-full font-poppins !h-[44px] !bg-rose-500 !border-none !text-white !text-[15px] !rounded-full !font-medium hover:!bg-rose-600 transition-colors"
									:loading="loading"
								>
									Sign in
								</a-button>

								<!-- Divider -->
								<div class="relative flex items-center justify-center my-4">
									<div class="flex-grow border-t border-neutral-200"></div>
									<span class="flex-shrink mx-4 text-neutral-400 font-poppins text-sm">Or continue with</span>
									<div class="flex-grow border-t border-neutral-200"></div>
								</div>

								<!-- Social Login -->
								<div class="flex items-center justify-center gap-4">
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-google theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-facebook theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-twitter theme="filled" size="20" />
									</button>
									<button class="flex items-center justify-center w-10 h-10 rounded-full border border-neutral-200 hover:bg-neutral-100 text-neutral-400 hover:text-rose-600 transition-colors">
										<icon-park-tiktok theme="filled" size="20" />
									</button>
								</div>

								<!-- Register Link -->
								<div class="text-center mt-4">
									<span class="text-neutral-500 font-poppins text-sm">Don't have an account?</span>
									<a href="javascript:void(0)" class="text-rose-500 hover:text-rose-600 ml-1" @click="isLoginForm = false">Sign up</a>
								</div>
							</a-form>
						</template>
					</div>
				</div>
			</div>
		</transition>
	</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Google, Facebook, Twitter, Tiktok, Close } from '@icon-park/vue-next';
import { FormInstance } from '@arco-design/web-vue';
import { getUserProfile, signin, signup } from '@/api';
import { components } from '@/types/api';
import { useStore } from '@/stores';

type SigninFormData = {
    email: string
    password: string
}

type SignupFormData = {
    email: string
    code: string
    password: string
}

export default defineComponent({
    name: 'SigninModal',
    components: {
		'icon-park-google': Google,
		'icon-park-facebook': Facebook,
		'icon-park-twitter': Twitter,
		'icon-park-tiktok': Tiktok,
		'icon-park-close': Close
    },
    data() {
        return {
            visible: false,
            loading: false,
			cooldown: 0,
			isLoginForm: true,
			isCanSubmit: false,
            signupFormData: {
                email: '',
                code: '',
                password: ''
            } as SignupFormData,
            signinFormData: {
                email: '',
                password: ''
            } as SigninFormData,
            signupFormRules: {
                email: [
                    { required: true, message: 'Please enter your email' },
                    { type: 'email', message: 'Please enter a valid email' }
                ],
                code: [
                    { required: true, message: 'Please enter verification code' },
                    { match: /^[0-9]{6}$/, message: 'Please enter a 6-digit verification code' }
                ],
                password: [
                    { required: true, message: 'Please enter password' },
                    { minLength: 6, message: 'Must be 6-20 characters' },
                    { maxLength: 20, message: 'Must be 6-20 characters' },
                    { 
                        match: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{6,20}$/,
                        message: 'Must contain numbers, letters and special characters'
                    }
                ]
            },
            signinFormRules: {
                email: [
                    { required: true, message: 'Please enter your email' },
                    { type: 'email', message: 'Please enter a valid email' }
                ],
                password: [
                    { required: true, message: 'Please enter password' }
                ]
            }
        }
    },
    setup() {
        const store = useStore()
        return { 
			store
		}
    },	
    created() {
        // 监听全局状态变化
        this.$watch(
            () => (this.$root as any).$signin?.visible,
            (val) => {
                this.visible = val
            },
            { immediate: true }
        )
    },
    methods: {
        handleClose() {
            this.$signin.hide()
        },
        async sendcode() {
            if (this.cooldown > 0) return
            try {
                this.loading = true
                // TODO: 调用发送验证码接口
                this.cooldown = 60
                const timer = setInterval(() => {
                    this.cooldown--
                    if (this.cooldown <= 0) {
                        clearInterval(timer)
                    }
                }, 1000)
            } catch (error) {
                console.error(error)
            } finally {
                this.loading = false
            }
        },
        async handleSignupSubmit() {
            const form = this.$refs.signupFormRef as FormInstance;
            if (!form) {
                return;
            }
            await form.validate();
            if (!this.isCanSubmit) {
                return;
            }
            this.loading = true;
            try {
                const data = await signup({
                    email: this.signupFormData.email,
                    password: this.signupFormData.password,
                    code: this.signupFormData.code,
                });
                this.store.auth = data?.data as components['schemas']['SchemaUserTokens'];
                const user = await getUserProfile()
                this.store.user = user?.data as components['schemas']['SchemaUserOpen'];
                this.handleClose();
            } catch (error) {
                //
            } finally {
                this.loading = false;
            }
        },
        handleSignupSuccess() {
            this.isCanSubmit = true;
        },
        handleSignupFailed() {
            this.isCanSubmit = false;
        },
        async handleSigninSubmit() {
            const form = this.$refs.signinFormRef as FormInstance;
            if (!form) {
                return;
            }
            await form.validate();
            if (!this.isCanSubmit) {
                return;
            }
            this.loading = true;
            try {
                const data = await signin({
                    username: this.signinFormData.email,
                    password: this.signinFormData.password,
                    type: 1
                });

                this.store.auth = data?.data as components['schemas']['SchemaUserTokens'];
                const user = await getUserProfile()
                this.store.user = user?.data as components['schemas']['SchemaUserOpen'];
                this.handleClose();
            } catch (error) {
                //
            } finally {
                this.loading = false;
            }
        },
        handleSigninSuccess() {
            this.isCanSubmit = true;
        },
        handleSigninFailed() {
            this.isCanSubmit = false;
        }
    }
});
</script>